package com.hyg.lib_common.loginpart;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.R;
import com.mobile.auth.gatewayauth.ActivityResultListener;
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

public class LoginFasterActivity extends AppCompatActivity {

    String info;
    String app_id = "1108033225";
    public static Tencent mTencent;
    PhoneNumberAuthHelper mAlicomAuthHelper;
    TokenResultListener mTokenListener;
    // IWXAPI 是第三方app和微信通信的openApi接口
    public IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_faster);
        init();
    }

    public void init(){
        mTokenListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                Log.i("lgb", "onTokenSuccess: " + s);
            }

            @Override
            public void onTokenFailed(String s) {
                Log.i("lgb", "onTokenFailed: " + s);
            }
        };
        mAlicomAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenListener);
        mAlicomAuthHelper.setAuthSDKInfo("CS0btwjtL9RmXgaLJ8e5Eho2mhS5FVfVBEABMLSi672mVUUQNBMVNd1HE/tv4y7qGXt2IIyoMOMvNCoVEX3UezJXdqPWbNPpBdgNZTevHuTwvCjwvO2qMNq8I2MOilxars/OiY3PbMQCsRTQtNJ1U6/sjyoKDXhNOPrEAC3IaLczbLxBSGSnswf3O0M0fi6SkWFCDkS3E8ldeyfexJzEvOeII6eMoq1F/EPWGSBeIzpJWOUsMu+I/H9zJ0m/BYhGxzuoYLy/hoP9ST4icPBqmY8GAlzJarNcuTQkyZ2Wt5r6QiGSxtMPJgIi2DJemWCZ");
        mAlicomAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                .setNavText("登录")
                .setNavTextSize((int) getResources().getDimension(R.dimen.title_text_size))
                .setLogBtnText("一键登录")
                .setNavTextColor(getResources().getColor(R.color.MainThemeColor3))
                .setStatusBarColor(getResources().getColor(R.color.white))
                .setLightColor(true)
                .setLogoImgPath("logo_512x")
                .setLogoWidth((int) getResources().getDimension(R.dimen.logo_width))
                .setLogoHeight((int) getResources().getDimension(R.dimen.logo_width))
                .setSloganHidden(true)
                .setSwitchAccText("账号密码登录")
                .setSwitchAccHidden(true)
                .setLogBtnBackgroundPath("shape_corner_main_boder")
                .setLogBtnTextColor(Color.WHITE).setLogoHidden(false)
                .setNavColor(0xffffffff)
                .setNumberColor(Color.BLACK)
                .setNumberSize(26)
                .setPageBackgroundPath("shape_bg")
                .setAppPrivacyOne("隐私政策与免责声明", "http://app.tcmhyg.com/med/privacy.html")
                .setWebNavTextColor(getResources().getColor(R.color.MainThemeColor3))
                .setWebNavTextSize((int) getResources().getDimension(R.dimen.title_text_size))
                .setWebNavColor(getResources().getColor(R.color.white))
                .setNavReturnScaleType(ImageView.ScaleType.CENTER_INSIDE)
                .setWebNavReturnImgPath("back")
//                .setDialogWidth(320)
//                .setDialogHeight(600)
                .create());

        mAlicomAuthHelper.addAuthRegisterXmlConfig(new AuthRegisterXmlConfig.Builder().setLayout(R.layout.layout_third_login, new AbstractPnsViewDelegate() {
                    @Override
                    public void onViewCreated(View view) {
                        //这⾥返回的View，不建议⽤强引⽤，如果要⽤，请及时释放，否则容易造成 内存泄漏
                        // findViewById(R.id.xxxx).setOnClickListener(new View.OnCli ckListener() {  @Override public void onClick(View v) { //do something  }  });  }  }).build());
                        findViewById(R.id.ln_wechat_login).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Log.i("lgb", "onClick: qq");
                                if (!mTencent.isSessionValid()) {
                                    mTencent.login(LoginFasterActivity.this, "all", loginListener);
                                }/** 登陆过注销之后在登录 */
                                else {
                                    mTencent.logout(LoginFasterActivity.this);
                                    mTencent.login(LoginFasterActivity.this, "all", loginListener);
                                }
                            }
                        });
                        findViewById(R.id.ln_password_login).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Log.i("lgb", "onClick: wechat");
                                SendAuth.Req req = new SendAuth.Req();
                                req.scope = "snsapi_userinfo";
                                req.state = "wechat_sdk_demo_test";
                                BaseApplication.api.sendReq(req);
                            }
                        });

//                        findViewById(R.id.tv_login_password).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                Log.i("lgb", "onClick: ACCOUNT");
//                            }
//                        });
//
//                        findViewById(R.id.tv_login_phone).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                Log.i("lgb", "onClick: ACCOUNT");
//                            }
//                        });

                    }
                }
        )
                .build())

        ;

        mAlicomAuthHelper.setActivityResultListener(new ActivityResultListener() {
            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                Log.i("lgb", "onActivityResult: 22222");
                Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
                if (requestCode == Constants.REQUEST_API) {
                    if (resultCode == Constants.REQUEST_LOGIN) {
                        Tencent.handleResultData(data, loginListener);
                    }
                }
            }
        });
        mAlicomAuthHelper.getLoginToken(this, 5000);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        Log.i("lgb", "onActivityResult: 11111");
        Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_LOGIN) {
                Tencent.handleResultData(data, loginListener);
            }
        }
    }


    IUiListener loginListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            if (null == o) {
                Log.i("lgb", "onComplete: 登录失败 ==空");
                return;
            }
            JSONObject jsonResponse = (JSONObject) o;
            initOpenidAndToken(jsonResponse);
            updateUserInfo();
        }

        @Override
        public void onError(UiError uiError) {
            Log.i("lgb", "onError: ");
        }

        @Override
        public void onCancel() {
            Log.i("lgb", "onCancel: ");
        }

        @Override
        public void onWarning(int i) {
            Log.i("lgb", "onWarning: " + i);
        }
    };

    /**
     * QQ登录获取用户id token
     */
    public static void initOpenidAndToken(JSONObject jsonObject) {
        Log.i("lgb", "initOpenidAndToken: " + jsonObject.toString());
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            Log.i("lgb", "initOpenidAndToken: token=" + token);
            Log.i("lgb", "initOpenidAndToken: openId" + openId);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }

    /**
     * QQ登录获取用户信息
     */
    private void updateUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {
            IUiListener listener = new IUiListener() {
                @Override
                public void onError(UiError e) {
                    Log.i("lgb", "updateUserInfo onError: " + e.errorDetail);
                }

                @Override
                public void onComplete(final Object response) {
                    JSONObject jsonObject = (JSONObject) response;
                    Log.i("lgb", "onComplete: " + jsonObject.toString());
                }

                @Override
                public void onCancel() {
                    Log.i("lgb", "updateUserInfo onCancel: ");
                }

                @Override
                public void onWarning(int i) {
                    Log.i("lgb", "updateUserInfo onWarning: " + i);
                }
            };
            UserInfo mInfo = new UserInfo(this, mTencent.getQQToken());
            mInfo.getUserInfo(listener);
        } else {

        }
    }

}